package com.dcivision.dms.core;

import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.impl.LogFactoryImpl;

import uk.ltd.getahead.dwr.ExecutionContext;

import com.dcivision.dms.bean.DmsDocument;
import com.dcivision.dms.bean.DmsValidation;
import com.dcivision.dms.dao.DmsDocumentDAObject;
import com.dcivision.framework.ApplicationContainer;
import com.dcivision.framework.ApplicationException;
import com.dcivision.framework.DWRFacade;
import com.dcivision.framework.DataSourceFactory;
import com.dcivision.framework.ErrorConstant;
import com.dcivision.framework.GlobalConstant;
import com.dcivision.framework.MessageResourcesFactory;
import com.dcivision.framework.SessionContainer;
import com.dcivision.framework.TextUtility;
import com.dcivision.framework.Utility;
import com.dcivision.workflow.bean.MtmWorkflowProgressSystemObject;
import com.dcivision.workflow.dao.MtmWorkflowProgressSystemObjectDAObject;
import com.dcivision.workflow.dao.WorkflowProgressDAObject;

public class DmsDocumentListDeleteFacade extends DWRFacade {
  protected Log log = new LogFactoryImpl().getInstance(this.getClass());
  Connection conn = null;
  
  public DmsDocumentListDeleteFacade() {
    super();
    
  }
  
  private HttpSession getHttpSession(){
    return ExecutionContext.get().getSession();
  }
  
  public String opListDelete(String[] selectedID,boolean isNotDeleteRelationship){
    SessionContainer sessionContainer = this.getSessionContainer();
    conn = this.getDBConnection();
    DocumentValidateManager docValidateManager = new DocumentValidateManager(sessionContainer, conn);
    DocumentOperationManager docOperationManager = new DocumentOperationManager(sessionContainer, conn);
    DocumentRetrievalManager docRetrievalManager = new DocumentRetrievalManager(sessionContainer, conn);
    DmsDocumentDAObject dmsDocumentDAO = new DmsDocumentDAObject(sessionContainer, conn);
    ApplicationContainer container = (ApplicationContainer)this.getHttpSession().getServletContext().getAttribute(GlobalConstant.APPLICATION_CONTAINER_KEY);
    MtmWorkflowProgressSystemObjectDAObject mtmWorkflowProgressSystemObjectDAO=new MtmWorkflowProgressSystemObjectDAObject(sessionContainer,conn);
    WorkflowProgressDAObject workflowProgressDAO=new WorkflowProgressDAObject(sessionContainer,conn);
    StringBuffer message = new StringBuffer();

    try {
      //Update By Jim Zhou          2007/01/09        EIP-1292
      //String[] selectedID = form.getBasicSelectedID();
      //selectedID = docValidateManager.validatorFilterDocID(selectedID);
      //boolean isIgnoreDeleteShortcut = ((ListDmsDocumentForm)form).isIgnoreDeleteShortcut();
      
      for (int n=0; n<selectedID.length; n++) {
        Integer srcDocumentId = TextUtility.parseIntegerObj(selectedID[n]);
        DmsDocument sourceDocument = (DmsDocument)dmsDocumentDAO.getObjectByID(srcDocumentId);
        //bill add  for EIP-1483 start
        List mtmWorkflowProgressSystemObjectList=mtmWorkflowProgressSystemObjectDAO.getListByBeanClassNameObjectID(sourceDocument.getClass().getName(), sourceDocument.getID());
        if(!Utility.isEmpty(mtmWorkflowProgressSystemObjectList)){
          MtmWorkflowProgressSystemObject mtmWorkflowProgressSystemObject=(MtmWorkflowProgressSystemObject)mtmWorkflowProgressSystemObjectList.get(0);
          boolean isComplete=workflowProgressDAO.checkProgressComplete(mtmWorkflowProgressSystemObject.getTrackID());
          if(!isComplete){
            //This document binding of workflow is not be complete,so can not to delete
            message.append(MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), "errors.dms.delete_operation_failed",sourceDocument.getDocumentName()));
            break;
          }
        }
        //bill add for EIP-1483 end
        DmsValidation validation = docValidateManager.validateDeleteAction(sourceDocument, isNotDeleteRelationship);
        
        String cacheKey = "D"+sessionContainer.getSessionID()+""+System.currentTimeMillis();
        try {
          List deleteDocumentIds = validation.getLstIdAccept();
          //boolean success = true;
          boolean success = container.checkAndLockDocumentOperationID(cacheKey, deleteDocumentIds, "ACDIMU");
          if (!success) {
            message.append(MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(),"errors.dms.fail_to_delete", docRetrievalManager.getLocationPath(srcDocumentId)) + "\n");
            message.append(MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(),"errors.dms.cannot_edit_now") + "\n");
          }else {
            docOperationManager.deleteDocument(sourceDocument, validation);
            
            List lstIdHasRight = validation.getLstIdAccept();
            List lstIdMisRight = validation.getLstIdReject();
            List lstIdBeLocked = validation.getLstIdlocked();
            List lstIdBeDeleted = validation.getLstIdDeleted();
            List lstIdBeArchived = validation.getLstIdArchived();
            List lstIdRelationship = validation.getLstIdHaveRelationship();
            String locationPath = docRetrievalManager.getLocationPath(srcDocumentId);
            if (validation.isSuccess()) {
              message.append(MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(),"dms.message.document_deleted_success", locationPath, String.valueOf(lstIdHasRight.size())) + "\n");
            }else {
              message.append(MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(),"errors.dms.fail_to_delete", locationPath) + "\n");
              for (int i=0; i<lstIdMisRight.size(); i++) {
                message.append(MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(),"errors.dms.no_permission",docRetrievalManager.getLocationPath((Integer)lstIdMisRight.get(i))) + "\n");
              }
              for (int i=0; i<lstIdBeLocked.size(); i++) {
                message.append(MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(),"errors.dms.been_checkout",docRetrievalManager.getLocationPath((Integer)lstIdBeLocked.get(i))) + "\n");
              }
              for (int i=0; i<lstIdBeDeleted.size(); i++) {
                message.append(MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(),"errors.dms.been_deleted",docRetrievalManager.getLocationPath((Integer)lstIdBeDeleted.get(i))) + "\n");
              }
              for (int i=0; i<lstIdBeArchived.size(); i++) {
                message.append(MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(),"errors.dms.been_archived",docRetrievalManager.getLocationPath((Integer)lstIdBeArchived.get(i))) + "\n");
              }
              for (int i=0; i<lstIdRelationship.size(); i++) {
                message.append(MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(),"errors.dms.has_relationship",docRetrievalManager.getLocationPath((Integer)lstIdRelationship.get(i))) + "\n");
              }
              if (!Utility.isEmpty(lstIdHasRight)) {
                message.append(MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(),"dms.message.document_been_deleted",String.valueOf(lstIdHasRight.size())) + "\n");
              }
            }

            List clipboardList = (List)this.getHttpSession().getAttribute("DMS_CLIPBOARD");
            if (clipboardList!=null && !clipboardList.isEmpty()) {
              for (int i=0; i<clipboardList.size(); i++) {
                if(deleteDocumentIds.contains((Integer)clipboardList.get(i))) {
                  clipboardList.remove(i--);
                }
              }
            }
          }
        }catch (ApplicationException ex) {
          //throw ex;
          message.append(MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(),"errors.dms.delete_errors") + "\n");
        }catch (Exception ex) {
          //throw new ApplicationException(ex);
          message.append(MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(),"errors.dms.delete_errors") + "\n");
        }finally {
          container.unlockDmsDocumentOperationID(cacheKey);
        }
      }
      conn.commit();
    } catch (ApplicationException e) {
      log.error(e, e);
      message.append(MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(),"errors.dms.delete_errors") + "\n");
    } catch (Exception e) {
      log.error("Error in Scheduler.", e);
      message.append(MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(),ErrorConstant.SYS_SCHEDULER_ERROR));
    } finally {
      this.closeConnection();
    }
    return message.toString();
  }
  

  public String opListDelete2(String[] selectedID,String[] exSelectedIDs,boolean isNotDeleteRelationship){
    SessionContainer sessionContainer = this.getSessionContainer();
    conn = this.getDBConnection();
    DocumentValidateManager docValidateManager = new DocumentValidateManager(sessionContainer, conn);
    DocumentOperationManager docOperationManager = new DocumentOperationManager(sessionContainer, conn);
    DocumentRetrievalManager docRetrievalManager = new DocumentRetrievalManager(sessionContainer, conn);
    DmsDocumentDAObject dmsDocumentDAO = new DmsDocumentDAObject(sessionContainer, conn);
    ApplicationContainer container = (ApplicationContainer)this.getHttpSession().getServletContext().getAttribute(GlobalConstant.APPLICATION_CONTAINER_KEY);
    MtmWorkflowProgressSystemObjectDAObject mtmWorkflowProgressSystemObjectDAO=new MtmWorkflowProgressSystemObjectDAObject(sessionContainer,conn);
    WorkflowProgressDAObject workflowProgressDAO=new WorkflowProgressDAObject(sessionContainer,conn);
    StringBuffer message = new StringBuffer();

    try {
      //Update By Jim Zhou          2007/01/09        EIP-1292
      //String[] selectedID = form.getBasicSelectedID();
      //selectedID = docValidateManager.validatorFilterDocID(selectedID);
      //boolean isIgnoreDeleteShortcut = ((ListDmsDocumentForm)form).isIgnoreDeleteShortcut();
      
      for (int n=0; n<selectedID.length; n++) {
        Integer srcDocumentId = TextUtility.parseIntegerObj(selectedID[n]);
        DmsDocument sourceDocument = (DmsDocument)dmsDocumentDAO.getObjectByID(srcDocumentId);
        //bill add  for EIP-1483 start
        List documentIds = new ArrayList();      
        documentIds.add(sourceDocument.getID());
        documentIds = docRetrievalManager.getAllsubFolderDocIDsByObjectID(documentIds, sourceDocument.getRootID());    
        boolean isComplete = true;
        for(int d=0; d<documentIds.size(); d++) {
          Integer objectID = (Integer)documentIds.get(d);
          List mtmWorkflowProgressSystemObjectList=mtmWorkflowProgressSystemObjectDAO.getListByBeanClassNameObjectID(sourceDocument.getClass().getName(), objectID);
          if(!Utility.isEmpty(mtmWorkflowProgressSystemObjectList)){
            MtmWorkflowProgressSystemObject mtmWorkflowProgressSystemObject=(MtmWorkflowProgressSystemObject)mtmWorkflowProgressSystemObjectList.get(0);
            isComplete=workflowProgressDAO.checkProgressComplete(mtmWorkflowProgressSystemObject.getTrackID());
            if(!isComplete){
//            This document binding of workflow is not be complete,so can not to delete     
              message.append(MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), "errors.dms.delete_operation_failed",sourceDocument.getDocumentName()));
              break;
            }
          }
        }
        if(!isComplete){
          break;
        }
       
        //bill add for EIP-1483 end
        DmsValidation validation = docValidateManager.validateDeleteAction(sourceDocument, isNotDeleteRelationship);
        
        String cacheKey = "D"+sessionContainer.getSessionID()+""+System.currentTimeMillis();
        try {
          List deleteDocumentIds = validation.getLstIdAccept();
          //boolean success = true;
          boolean success = container.checkAndLockDocumentOperationID(cacheKey, deleteDocumentIds, "ACDIMU");
          if (!success) {
            message.append(MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(),"errors.dms.fail_to_delete", docRetrievalManager.getLocationPath(srcDocumentId)) + "\n");
            message.append(MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(),"errors.dms.cannot_edit_now") + "\n");
          }else {
            //docOperationManager.deleteDocument(sourceDocument, validation);
            docOperationManager.deleteDocument2(sourceDocument, exSelectedIDs, validation);
            
            List lstIdHasRight = validation.getLstIdAccept();
            List lstIdMisRight = validation.getLstIdReject();
            List lstIdBeLocked = validation.getLstIdlocked();
            List lstIdBeDeleted = validation.getLstIdDeleted();
            List lstIdBeArchived = validation.getLstIdArchived();
            List lstIdRelationship = validation.getLstIdHaveRelationship();
            String locationPath = docRetrievalManager.getLocationPath(srcDocumentId);
            if (validation.isSuccess()) {
              message.append(MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(),"dms.message.document_deleted_success", locationPath, String.valueOf(lstIdHasRight.size())) + "\n");
            }else {
              message.append(MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(),"errors.dms.fail_to_delete", locationPath) + "\n");
              for (int i=0; i<lstIdMisRight.size(); i++) {
                message.append(MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(),"errors.dms.no_permission",docRetrievalManager.getLocationPath((Integer)lstIdMisRight.get(i))) + "\n");
              }
              for (int i=0; i<lstIdBeLocked.size(); i++) {
                message.append(MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(),"errors.dms.been_checkout",docRetrievalManager.getLocationPath((Integer)lstIdBeLocked.get(i))) + "\n");
              }
              for (int i=0; i<lstIdBeDeleted.size(); i++) {
                message.append(MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(),"errors.dms.been_deleted",docRetrievalManager.getLocationPath((Integer)lstIdBeDeleted.get(i))) + "\n");
              }
              for (int i=0; i<lstIdBeArchived.size(); i++) {
                message.append(MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(),"errors.dms.been_archived",docRetrievalManager.getLocationPath((Integer)lstIdBeArchived.get(i))) + "\n");
              }
              for (int i=0; i<lstIdRelationship.size(); i++) {
                message.append(MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(),"errors.dms.has_relationship",docRetrievalManager.getLocationPath((Integer)lstIdRelationship.get(i))) + "\n");
              }
              if (!Utility.isEmpty(lstIdHasRight)) {
                message.append(MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(),"dms.message.document_been_deleted",String.valueOf(lstIdHasRight.size())) + "\n");
              }
            }

            List clipboardList = (List)this.getHttpSession().getAttribute("DMS_CLIPBOARD");
            if (clipboardList!=null && !clipboardList.isEmpty()) {
              for (int i=0; i<deleteDocumentIds.size(); i++) {
                if(clipboardList.contains((Integer)deleteDocumentIds.get(i))) {
                    clipboardList.remove(i--);
                }
              }
            }
          }
        }catch (ApplicationException ex) {
          //throw ex;
          message.append(MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(),"errors.dms.delete_errors") + "\n");
        }catch (Exception ex) {
          //throw new ApplicationException(ex);
          message.append(MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(),"errors.dms.delete_errors") + "\n");
        }finally {
          container.unlockDmsDocumentOperationID(cacheKey);
        }
      }
      conn.commit();
    } catch (ApplicationException e) {
      log.error(e, e);
      message.append(MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(),"errors.dms.delete_errors") + "\n");
    } catch (Exception e) {
      log.error("Error in Scheduler.", e);
      message.append(MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(),ErrorConstant.SYS_SCHEDULER_ERROR));
    } finally {
      this.closeConnection();
    }
    return message.toString();
  }

  private Connection getDBConnection(){
    if(this.conn!=null){
      return conn;
    }else{
      try{
        conn=DataSourceFactory.getConnection();
      }catch(Exception e){
        log.error("get Connection error!");
      }
      return conn;
    }
  }
  
  private void closeConnection() {
    if(this.conn != null ){
      try { conn.close(); } catch (Exception ignore) {} finally { conn = null; }
      log.info("Close Connection Succeed");
    }
  }
}
